package utils

import (
	"fmt"
	consulapi "github.com/hashicorp/consul/api"
	logging "github.com/sirupsen/logrus"
)

var (
	consulAddress    = "127.0.0.1:8500"
	localIp          = "127.0.0.1"
	localPort        = 8080
	registrationID   = "go-kit"
	registrationName = "go-kit"
)

var ConsulClient *consulapi.Client

// 创建连接consul服务配置  consul agent -dev
func init() {
	config := consulapi.DefaultConfig()
	config.Address = consulAddress
	client, err := consulapi.NewClient(config)
	if err != nil {
		logging.Error("consul client error : ", err)
	}
	ConsulClient = client
}

func SetServiceInfo(name string, port int) {
	registrationName = name
	localPort = port
}

func ConsulRegister() {

	// 创建注册到consul的服务到
	registration := new(consulapi.AgentServiceRegistration)
	registration.ID = registrationID
	registration.Name = registrationName
	registration.Port = localPort
	registration.Tags = []string{"v1"}
	registration.Address = localIp

	// 增加consul健康检查回调函数
	check := new(consulapi.AgentServiceCheck)
	check.HTTP = fmt.Sprintf("http://%s:%d", registration.Address, registration.Port)
	check.Timeout = "5s"
	check.Interval = "5s"
	check.DeregisterCriticalServiceAfter = "30s" // 故障检查失败30s后 consul自动将注册服务删除
	registration.Check = check

	// 注册服务到consul
	err := ConsulClient.Agent().ServiceRegister(registration)
	if err != nil {
		logging.Error("consul client.Agent().ServiceRegister error : ", err)
	}

}

// 取消注册 报错
func ConsulCancelRegister() {
	ConsulClient.Agent().ServiceDeregister(registrationID)
}
